from starlette.responses import JSONResponse

from models.user import User
from tools.hash import hash_password
from fastapi import HTTPException

async def query_all_user(name: str = None, role: str = None, level: int = None, from_place: str = None) -> list[User]:
        query = User.all()

        if name: query = query.filter(name=name)

        if role: query = query.filter(role=role)

        if level: query = query.filter(level=level)

        if from_place: query = query.filter(from_place=from_place)

        users = await query  # 执行查询
        if not users:
            raise HTTPException(status_code=403, detail="未找到匹配用户")
        return users

async def add_user(username: str, user: str, password: str, role: str, from_place: str) -> dict:
    hashPassword = await hash_password(password)
    if await User.get_or_none(name=username):
        return {"msg": "用户名已存在"}
    con = await User.create(name=username, user= user, hash_password=hashPassword, role=role, level=1, active=False, from_place= from_place)
    if con:
        return {"msg": "创建档案成功"}
    else:
        return {"msg": "创建档案失败"}

async def delete_user_by_name(name) -> dict:
    user = await User.get_or_none(name=name)

    if user:
        await user.delete()
        return {"msg": "删除档案成功"}
    else:
        return {"msg": "删除档案失败"}

async def update_user_by_name(name: str, role: str, level: int, from_place: str, active: bool) -> dict:
    user_data = await User.get_or_none(name=name)
    if user_data:
        await user_data.update_from_dict(
            {
                "name": name,
                "role": role,
                "level": level,
                "from_place": from_place,
                "active": active
            }
        )
        await user_data.save()
        return JSONResponse(content={"msg": "更新档案成功"}, status_code=200)
    else:
        return HTTPException(status_code=403, detail="未找到匹配用户")

